package tcc.wa.presenter;

import android.util.Log;
import tcc.wa.R;
import tcc.wa.model.AlertType;
import tcc.wa.presenter.datasource.AlertTypeDataSource;
import tcc.wa.presenter.datasource.HoursInAdvanceDataSource;
import tcc.wa.presenter.view.AlertEnrollmentView;
import tcc.wa.service.AlertService;
import tcc.wa.service.factory.ServiceFactory;

/**
 * Presenter class for Alert enrollment.
 */
public class AlertEnrollmentPresenter {

	private String TAG = "AlertEnrollmentPresenter";
	
	private final AlertEnrollmentView view;
	
	private final AlertService alertService;
	
	public AlertEnrollmentPresenter(AlertEnrollmentView view) {
		this.view = view;
		alertService = ServiceFactory.getAlertService(view.getContext());
	}
	
	/**
	 * Called by the view when it's created.
	 */
	public void onCreate() {
		view.initView(R.layout.alert_enrollment);
		AlertTypeDataSource typeDataSource = new AlertTypeDataSource();
		HoursInAdvanceDataSource hoursInAdvanceDataSource = new HoursInAdvanceDataSource();
		view.setAlertTypeList(typeDataSource.Select());
		view.setHoursInAdvanceList(hoursInAdvanceDataSource.Select());
	}
	
	/**
	 * Creates an alert.
	 *
	 * @param type the alert type
	 * @param value the value
	 * @param hoursInAdvance the number of hours in advance
	 */
	public void createAlert(AlertType type, double value, int hoursInAdvance) {
		try {
			alertService.save(type, value, hoursInAdvance);
			view.finishEnrollment();
		} catch (Exception e) {
			Log.e(TAG, "Error while trying to save alert: " + e.getMessage() + "\n" + e.toString());
			view.showToast("Erro ao salvar alerta");
		}
	}
	
	/**
	 * Cancels alert enrollment.
	 */
	public void cancelAlertEnrollment() {
		view.finishEnrollment();
	}
}
